#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include "wrap.h"
#include "wrap.c"
void free_process(int sig){
    pid_t pid;
    while(1){
        //-1为任意子进程，WNOHANG不阻塞
        pid=waitpid(-1 ,NULL,WNOHANG);
        if(pid<=0){
            break;
        }else{
            printf("child pid=%d\n",pid);
        }
    }
}


int main(int argc,char *argv[]){
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set,SIGCHLD);
    sigprocmask(SIG_BLOCK,&set,NULL);

    //socket bind
    int lfd=tcp4bind(8008,NULL);
    //listen
    Listen(lfd,128);

    struct sockaddr_in cliaddr;
    socklen_t len=sizeof(cliaddr);
    while(1){
        char ip[16]="";
        int cfd=Accept(lfd,(struct sockaddr *)&cliaddr,&len);
        printf("new client ip=%s port=%d\n",inet_ntop(AF_INET,&cliaddr.sin_addr.s_addr,ip,16),ntohs(cliaddr.sin_port));
        //创建子进程
        pid_t pid;
        pid=fork();
        if(pid<0){
            perror("");
            exit(0);
        }
        //子进程
        else if(0==pid){
            //关闭lfd
            close(lfd);
            while(1){
                char buf[1024]="";
                int n=read(cfd,buf ,sizeof(buf));
                if(n<0){
                    perror("");
                    close(cfd);
                    exit(0);
                }else if(0==n){
                    printf("client close\n");
                    close(cfd);
                    exit(0); 
                }else{
                    printf("%s\n",buf);
                    write(cfd,buf,n);   
                }
            }
        }else//父进程
        {
            close(cfd);

            struct sigaction act;
            act.sa_flags=0;
            //信号处理函数
            act.sa_handler=free_process;
            //清空信号阻塞集
            sigemptyset(&act.sa_mask);
            //修改信号设置
            sigaction(SIGCHLD,&act,NULL);
            //从信号阻塞集中删除SIGCHLD
            sigprocmask(SIG_UNBLOCK,&set,NULL);

        }
    }
    close(lfd);
    return 0;
}

